from rest_framework.filters import BaseFilterBackend


class SearchByName(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        name = request.GET.get('name')
        queryset = queryset.filter(name__startswith=name)
        return queryset


class SearchByPrice(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        price_gt = request.GET.get('price_gt')
        price_lt = request.GET.get('price_lt')
        queryset = queryset.filter(price__gt=price_gt,price__lt=price_lt)
        return queryset



from django_filters.filterset import FilterSet
from . import models
from django_filters import filters
class CourseFilterSet(FilterSet):
    # 区间过滤：field_name关联的Model字段；lookup_expr设置规则；gt是大于，gte是大于等于；
    min_price = filters.NumberFilter(field_name='price', lookup_expr='gte')
    max_price = filters.NumberFilter(field_name='price', lookup_expr='lte')
    class Meta:
        model = models.Course
        # 如果过滤条件仅仅就是Model已有的字段，方式一更好
        # 但是方式二可以自定义过滤字段
        fields = ['course_category','min_price', 'max_price']

